package com.gs.thunder_manage.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/10/11 0011
 */
public class HttpUtils {

    //controller返回：
    // return HttpUtils.buildStringResponse("success",HttpStatus.OK);
    //OK(200, "OK"),
    //BAD_REQUEST(400, "Bad Request"),
    //NOT_FOUND(404, "Not Found"),
    //METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    //NOT_ACCEPTABLE(406, "Not Acceptable"),
    //INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    public static ResponseEntity<String> buildStringResponse(String str, HttpStatus status) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "text/plain;charset=utf-8;");
        return new ResponseEntity<>(str, responseHeaders, status);
    }

    public static String request(String url) {
        StringBuffer sbf = new StringBuffer();
        String result = null;
        BufferedReader reader = null;
        try {
            URL mUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            System.out.print("request->" + e.getMessage());
        } finally {
            return result;
        }
    }

}
